package com.simtop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.simtop.common.ServerResponse;
import com.simtop.controller.UserController;
import com.simtop.dao.CountDao;
import com.simtop.dao.OperateDao;
import com.simtop.dao.UserDao;
import com.simtop.pojo.Operate;
import com.simtop.pojo.User;
import com.simtop.service.JwtLoginService;
import com.simtop.util.JwtUtil;
import com.simtop.util.SHA256Util;
import com.simtop.vo.SuccessVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * JWT业务验证类
 */
@Service
public class JwtLoginServiceImpl implements JwtLoginService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private CountDao countDao;

    @Autowired
    private OperateDao operateDao;

    Logger logger = LoggerFactory.getLogger(JwtLoginServiceImpl.class);

    @Override
    public SuccessVo login(User user) {
        User u = userDao.checkLoginNameOrEmail(user.getLoginName());
        if(u == null){
            SuccessVo successVo = new SuccessVo();
            successVo.setMsg("登录信息不存在");
            return successVo;
        }
        //如果登陆成功
        if(u.getPassword().equals(SHA256Util.generateShaPwd(user.getPassword()))){

            //使用JWT加密生成token todo
            //置空密码
            u.setPassword(StringUtils.EMPTY);
            // todo important token有效期24个小时
            String token = JwtUtil.sign(u,60*60*24*1000L);
            Integer id = u.getId();
            String avatar = userDao.findImage(id);

            Integer ids = userDao.setcountid(id);
            //插入
            Integer last = ids + 1;
            userDao.savecountid(last,id);
            userDao.savetime(new Date(),id);
            try {
                String hostAddress = InetAddress.getLocalHost().getHostAddress();
                userDao.saveip(hostAddress,id);
            }
            catch (Exception e){

            }
            /**
             * todo 统计网站访问次数：登陆成功后统计次数变量count加1
             */
            int num = countDao.selectCount();
            int count = ++num;
            countDao.updateOne(count);
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            logger.warn("登录时间:{} 登录id:{} 登录用户:{} ",simpleDateFormat.format(date),u.getId(),u.getUsername());
            user.setPassword(StringUtils.EMPTY);
            Operate operate = new Operate("后台用户登录",u.getUsername(),u.getRoleId(),"登录成功",new Date(), JSONObject.toJSONString(user));
            operateDao.insertOperate(operate);

            SuccessVo successVo = new SuccessVo();
            successVo.setMsg("登录成功");
            successVo.setAvatar(avatar);
            successVo.setData(token);
            successVo.setStatus(0);
            return successVo;
        }
        Operate operate = new Operate("后台用户登录",u.getUsername(),u.getRoleId(),"登录失败,登录密码错误",new Date(), JSONObject.toJSONString(user));
        operateDao.insertOperate(operate);
        //return ServerResponse.createByErrorMsg("登录密码错误");
        SuccessVo successVo = new SuccessVo();
        successVo.setStatus(1);
        successVo.setMsg("登录失败");
        return successVo;
    }





}
